package okw.gui.wizards;

import java.util.ArrayList;

import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;

import okw.database.Terminal;

public class CreateConfigurationWizardPageTwo extends WizardPage {
	private ArrayList<ConfigurationInputGUI> selectedTerminalsGUI;

	public ArrayList<ConfigurationInputGUI> getSelectedTerminalsGUI() {
		return selectedTerminalsGUI;
	}

	private ScrolledComposite scrolledContainer;
	private Composite container;

	public CreateConfigurationWizardPageTwo() {
		super("Krok 2.");
		setTitle("Krok 2.");
		setDescription("Prosze wprowadzic wszystkie dane konfiguracyjne wybranych Okregowych Komisji Wyborczych");

		selectedTerminalsGUI = new ArrayList<ConfigurationInputGUI>();
	}

	public void createControl(Composite parent) {
		scrolledContainer = new ScrolledComposite(parent, SWT.V_SCROLL
				| SWT.BORDER);
		// Required to avoid an error in the system
		setControl(scrolledContainer);
	}

	// Metoda wywolywana, do zapelnienia formularzy konfiguracyjnych w kroku drugim wizarda
	public void onEnterPage(int[] pageOneSelectionIndices) {
		
		if(container != null) {
			container.dispose();
		}
		container = new Composite(scrolledContainer, SWT.NONE);
		scrolledContainer.setContent(container);
		
		GridLayout gridLayout = new GridLayout();
		container.setLayout(gridLayout);
		
		// Dodajemy listenera, celem weryfikacji, czy wszystkie pola sa wypelnione
		// TODO: zrobic, zeby obslugiwalo:D
		container.addKeyListener(new KeyListener() {
			
			public void keyReleased(KeyEvent arg0) {
				getWizard().getContainer().updateButtons();
				
			}
			
			public void keyPressed(KeyEvent arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		ArrayList<Terminal> terminalList = ((CreateConfigurationWizardWindow) getWizard()).getTerminalList();
		
		for (int i = 0; i < selectedTerminalsGUI.size(); i++) {
			selectedTerminalsGUI.get(i).getGroup().dispose();
			selectedTerminalsGUI.remove(i);
		}
		for (int i = 0; i < pageOneSelectionIndices.length; i++) {
			selectedTerminalsGUI.add(new ConfigurationInputGUI(container,
					terminalList.get(pageOneSelectionIndices[i])));
		}
		container.pack();
		

	}
	
	public boolean canFinish() {
		boolean canFinish = true;
		for (int i = 0; i < selectedTerminalsGUI.size() && canFinish; i++) {
			ConfigurationInputGUI ciGUI = selectedTerminalsGUI.get(i);
			if(ciGUI.getCipherKeyText().getText() == "" || ciGUI.getIpText().getText() == "" || ciGUI.getPasswordText().getText() == "") {
				canFinish = false;
			}
		}
		return canFinish;
	}
}

